package com.lottery.im.module.chat.ui;

import android.Manifest;
import android.content.Intent;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;
import butterknife.BindView;
import butterknife.OnClick;
import com.bumptech.glide.Glide;
import com.bumptech.glide.request.RequestOptions;
import com.lottery.im.R;
import com.lottery.im.base.BaseSwipeFragment;
import com.lottery.im.constant.Constants;
import com.lottery.im.constant.RxBusCode;
import com.lottery.im.module.chat.adapter.GroupProfileMemberAdapter;
import com.lottery.im.module.chat.presenter.GroupProfilePresenter;
import com.lottery.im.module.chat.view.GroupProfileView;
import com.lottery.im.module.setting.ui.MyQrCodeFragment;
import com.lottery.im.module.tim.event.MessageEvent;
import com.lottery.im.module.tim.message.Message;
import com.lottery.im.module.tim.message.TextMessage;
import com.lottery.im.module.tim.model.GroupInfo;
import com.lottery.im.module.tim.model.GroupMemberProfile;
import com.lottery.im.util.DisplayHelper;
import com.lottery.im.util.rxbus.RxBus;
import com.lottery.im.util.rxbus.Subscribe;
import com.lottery.im.util.transformations.CropCircleTransformation;
import com.lottery.im.widget.NoScrollGridView;
import com.lottery.im.widget.ShSwitchView;
import com.lottery.im.widget.dialog.BottomSelectDialog;
import com.lottery.im.widget.dialog.ConfirmWarnDialogBuilder;
import com.lzy.imagepicker.ImagePicker;
import com.lzy.imagepicker.bean.ImageItem;
import com.lzy.imagepicker.ui.ImageGridActivity;
import com.lzy.imagepicker.view.CropImageView;
import com.tbruyelle.rxpermissions2.RxPermissions;
import com.tencent.imsdk.TIMConversation;
import com.tencent.imsdk.TIMConversationType;
import com.tencent.imsdk.TIMGroupMemberInfo;
import com.tencent.imsdk.TIMGroupMemberRoleType;
import com.tencent.imsdk.TIMGroupReceiveMessageOpt;
import com.tencent.imsdk.TIMManager;
import com.tencent.imsdk.TIMMessage;
import com.tencent.imsdk.TIMUserProfile;
import com.tencent.imsdk.TIMValueCallBack;
import io.reactivex.Observer;
import io.reactivex.disposables.Disposable;
import java.util.ArrayList;
import java.util.List;

/**
 * 群资料
 */
public class GroupProfileFragment extends BaseSwipeFragment<GroupProfilePresenter> implements
    GroupProfileView {

  private final static String ID_KEY = "ID_KEY";

  public static GroupProfileFragment create(String id) {
    GroupProfileFragment fragment = new GroupProfileFragment();
    Bundle b = new Bundle();
    b.putString(ID_KEY, id);
    fragment.setArguments(b);
    return fragment;
  }

  @BindView(R.id.tv_title) TextView mTvTitle;
  @BindView(R.id.tv_member_num) TextView mTvMemberNum;
  @BindView(R.id.grid_member) NoScrollGridView mGridMember;
  @BindView(R.id.iv_portrait) ImageView mIvPortrait;
  @BindView(R.id.tv_name) TextView mTvName;
  @BindView(R.id.tv_group_card) TextView mTvGroupCard;
  @BindView(R.id.tv_notice) TextView mTvNotice;
  @BindView(R.id.tv_error) TextView mTvError;
  @BindView(R.id.sw_notiy_type) ShSwitchView mSwNotiyType;
  @BindView(R.id.sw_excuse) ShSwitchView mSwExcuse;
  @BindView(R.id.layout_excuse) LinearLayout mLayoutExcuse;
  @BindView(R.id.btn_operation) Button mBtnOperation;
  @BindView(R.id.layout_member) RelativeLayout mLayoutMember;

  private String mIdentify;
  private TIMGroupMemberRoleType mRole;

  private List<GroupMemberProfile> mGroupMemberProfiles;
  private GroupProfileMemberAdapter mAdapter;
  private boolean isOpe = false;

  // 群名片
  private static final int NAMECARD_REQUEST_CODE = 88;
  // 群名称
  private static final int GROUPNAME_REQUEST_CODE = 888;
  // 拍照
  private final static int PICK_PHOTO_REQCODE = 8888;
  // 图片选择
  private final static int PICK_IMAGE_REQCODE = 99;
  // 踢人
  private final static int DELETE_MEMBER_REQCODE = 999;
  // 邀请入群
  private final static int INVITE_MEMBER_REQCODE = 9999;
  // 群成员列表返回
  private final static int VIP_INFO_REQCODE = 123;

  @Override protected int getLayoutResId() {
    return R.layout.fragment_group_profile;
  }

  @Override protected void initPresenter() {
    presenter = new GroupProfilePresenter(getActivity(), this, this);
    presenter.init();
  }

  @Override public void initView() {
    RxBus.get().register(this);
    mIdentify = getArguments().getString(ID_KEY);
    initUI();
    mGroupMemberProfiles = new ArrayList<>();
    mAdapter = new GroupProfileMemberAdapter(mActivity, mGroupMemberProfiles, mRole);
    mGridMember.setAdapter(mAdapter);
    mGridMember.setOnItemClickListener((parent, view, position, id) -> {
      if (!isOpe) {
        showToast("无此操作权限");
        return;
      }
      if (position == mGroupMemberProfiles.size() - 1) {
        startFragmentForResult(DeleteGroupMemberFragment.create(mIdentify),
            DELETE_MEMBER_REQCODE);
      } else if (position == mGroupMemberProfiles.size() - 2) {
        startFragmentForResult(InviteGroupMemberFragment.create(mIdentify),
            INVITE_MEMBER_REQCODE);
      } else {
        startFragment(MemberVipFragment.create(mIdentify));
      }
    });
    presenter.getSelfInfo(mIdentify);
    presenter.getGroupMembers(1, mIdentify);
    if (isOpe) {
      presenter.getGroupDetailInfo(mIdentify);
    }
  }

  @OnClick({
      R.id.iv_back, R.id.layout_member, R.id.layout_portrait, R.id.layout_name,
      R.id.layout_group_card, R.id.layout_notice, R.id.layout_search_im, R.id.layout_qrcode,
      R.id.layout_clear, R.id.btn_operation
  }) public void onViewClicked(View view) {
    switch (view.getId()) {
      case R.id.iv_back:
        popBackStack();
        break;
      case R.id.layout_member:
        if (!isOpe) {
          showToast("无此操作权限");
          return;
        }
        startFragmentForResult(MemberVipFragment.create(mIdentify), VIP_INFO_REQCODE);
        break;
      case R.id.layout_portrait:
        // 修改头像
        if (!isOpe) {
          showToast("无此操作权限");
          return;
        }
        new BottomSelectDialog().create(getActivity(), "请选择打开方式", "相机", "相册",
            v -> {
              openPickImage(1);
              BottomSelectDialog.dismiss();
            }, v -> {
              openPickImage(2);
              BottomSelectDialog.dismiss();
            }).show();
        break;
      case R.id.layout_name:
        // 修改群名
        if (!isOpe) {
          showToast("无此操作权限");
          return;
        }
        startFragmentForResult(
            ModifySingleTextFragment.create(mIdentify, mTvName.getText().toString(),
                ModifySingleTextFragment.OpType.GROUPNAME), GROUPNAME_REQUEST_CODE);
        break;
      case R.id.layout_group_card:
        // 修改群名片
        startFragmentForResult(
            ModifySingleTextFragment.create(mIdentify, mTvGroupCard.getText().toString(),
                ModifySingleTextFragment.OpType.NAMECARD), NAMECARD_REQUEST_CODE);
        break;
      case R.id.layout_notice:
        // 群公告
        startFragment(GroupNoticeListFragment.create(mIdentify));
        break;
      case R.id.layout_search_im:
        // 查找聊天内容
        startFragment(ChatRecordSearchFragment.create(mIdentify));
        break;
      case R.id.layout_qrcode:
        // 群二维码
        startFragment(MyQrCodeFragment.create(GroupInfo.getInstance().getGroupName(mIdentify),
            GroupInfo.getInstance().getGroupAvatarUrl(mIdentify), mIdentify));
        break;
      case R.id.layout_clear:
        // 清空群聊天记录
        ConfirmWarnDialogBuilder.getInstance(mActivity)
            .setContent("是否删除群历史聊天记录？")
            .setCancel("取消", null)
            .setConfirm("确定", v -> presenter.clearMessage(mIdentify))
            .show();
        break;
      case R.id.btn_operation:

        String tip;

        if (mRole == TIMGroupMemberRoleType.Owner) {
          tip = "确定解散群聊？";
        } else {
          tip = "确定退出群聊？";
        }

        ConfirmWarnDialogBuilder.getInstance(mActivity)
            .setContent(tip)
            .setCancel("取消", null)
            .setConfirm("确定", v -> presenter.operation(mIdentify))
            .show();
        break;
    }
  }

  private void initUI() {
    String groupName = GroupInfo.getInstance().getGroupName(mIdentify);
    mTvTitle.setText(groupName + "的资料");
    mTvName.setText(groupName);
    Glide.with(mContext)
        .load(GroupInfo.getInstance().getGroupAvatarUrl(mIdentify))
        .apply(new RequestOptions()
            .bitmapTransform(new CropCircleTransformation())
            .placeholder(R.drawable.icon_conversation_de)
            .error(R.drawable.icon_conversation_de))
        .into(mIvPortrait);
    mRole = GroupInfo.getInstance().getRole(mIdentify);
    if (mRole == TIMGroupMemberRoleType.Owner) {
      isOpe = true;
      mLayoutExcuse.setVisibility(View.VISIBLE);
      mBtnOperation.setText("解散群聊");
    } else {
      mBtnOperation.setText("退出群聊");
      if (mRole == TIMGroupMemberRoleType.Admin) {
        isOpe = true;
        mLayoutExcuse.setVisibility(View.VISIBLE);
      } else {
        isOpe = false;
        mLayoutExcuse.setVisibility(View.GONE);
      }
    }

    String groupNotification = GroupInfo.getInstance().getGroupNotification(mIdentify);
    if (!TextUtils.isEmpty(groupNotification)) {
      if (groupNotification.contains(Constants.NOTICE_SEPARATE)) {
        mTvNotice.setText(groupNotification.substring(0,
            groupNotification.indexOf(Constants.NOTICE_SEPARATE)));
      } else {
        mTvNotice.setText(groupNotification);
      }
    }
    TIMGroupReceiveMessageOpt opt = GroupInfo.getInstance().getMessageOpt(mIdentify);
    if (opt == TIMGroupReceiveMessageOpt.ReceiveAndNotify) {
      mSwNotiyType.setOn(false);
    } else {
      mSwNotiyType.setOn(true);
    }

    // 消息免打扰开关
    mSwNotiyType.setOnSwitchStateChangeListener(
        isOn -> presenter.setReceiveMessageOpt(mIdentify, !isOn));
  }

  /**
   * 拉取那些非好友的成员资料
   * 由于tim返回群成员的信息是没有头像跟昵称的
   */
  private void getUsersProfile() {
    List<String> ids = new ArrayList<>();
    for (GroupMemberProfile memberProfile : mGroupMemberProfiles) {
      if (TextUtils.isEmpty(memberProfile.getAvatarUrl())) {
        ids.add(memberProfile.getIdentify());
      }
    }
    if (ids.size() > 0) presenter.getUsersProfile(ids);
  }

  /**
   * 打开图片选择
   *
   * @param type 1 相机 2 相册
   */
  private void openPickImage(int type) {
    new RxPermissions(getActivity()).request(Manifest.permission.CAMERA,
        Manifest.permission.READ_EXTERNAL_STORAGE)
        .subscribe(new Observer<Boolean>() {
          @Override public void onSubscribe(Disposable d) {

          }

          @Override public void onNext(Boolean aBoolean) {
            if (aBoolean) {

              int screenWidth = DisplayHelper.getScreenWidth(mActivity);
              ImagePicker.getInstance().setMultiMode(false);
              ImagePicker.getInstance().setCrop(true);
              ImagePicker.getInstance().setStyle(CropImageView.Style.CIRCLE);
              ImagePicker.getInstance().setFocusWidth(screenWidth / 3 * 2);
              ImagePicker.getInstance().setFocusHeight(screenWidth / 3 * 2);

              if (type == 1) {
                Intent intent = new Intent(mActivity, ImageGridActivity.class);
                intent.putExtra(ImageGridActivity.EXTRAS_TAKE_PICKERS, true); // 是否是直接打开相机
                startActivityForResult(intent, PICK_PHOTO_REQCODE);
              } else if (type == 2) {
                ImagePicker.getInstance().setShowCamera(false);  //显示拍照按钮
                Intent intent = new Intent(mActivity, ImageGridActivity.class);
                startActivityForResult(intent, PICK_IMAGE_REQCODE);
              }
            } else {
              showToast("你已拒绝访问相册和拍照权限～");
            }
          }

          @Override public void onError(Throwable e) {

          }

          @Override public void onComplete() {

          }
        });
  }

  @Override public void setNameCard(String nameCard) {
    mTvGroupCard.setText(nameCard);
  }

  @Override public void showMemberInfo(List<TIMGroupMemberInfo> timGroupMemberInfos) {
    mTvError.setVisibility(View.GONE);
    mLayoutMember.setVisibility(View.VISIBLE);
    mTvMemberNum.setText("共" + timGroupMemberInfos.size() + "人");
    mGroupMemberProfiles.clear();

    for (TIMGroupMemberInfo info : timGroupMemberInfos) {
      mGroupMemberProfiles.add(new GroupMemberProfile(info));
      if (mRole == TIMGroupMemberRoleType.Admin || mRole == TIMGroupMemberRoleType.Owner) {
        if (mGroupMemberProfiles.size() >= 8) break;
      } else {
        if (mGroupMemberProfiles.size() >= 10) break;
      }
    }
    if (mRole == TIMGroupMemberRoleType.Admin || mRole == TIMGroupMemberRoleType.Owner) {
      GroupMemberProfile profile = new GroupMemberProfile(null);
      mGroupMemberProfiles.add(profile);
      mGroupMemberProfiles.add(profile);
    }
    mAdapter.notifyDataSetChanged();
    getUsersProfile();
  }

  @Override public void refreshUsersProfile(List<TIMUserProfile> timUserProfiles) {
    for (int i = 0; i < mGroupMemberProfiles.size(); i++) {
      GroupMemberProfile memberProfile = mGroupMemberProfiles.get(i);
      if (null == memberProfile.getIdentify()) continue;
      for (TIMUserProfile userProfile : timUserProfiles) {
        if (memberProfile.getIdentify().equals(userProfile.getIdentifier())) {
          memberProfile.setAvatarUrl(userProfile.getFaceUrl());
          memberProfile.setNickName(userProfile.getNickName());
          break;
        }
      }
    }
    mAdapter.notifyDataSetChanged();
  }

  @Override public void setReceiveMessageOptFail() {
    mSwNotiyType.setOn(!mSwNotiyType.isOn());
    showToast("设置失败，请稍后再试");
  }

  @Override public void setSilenceSuc() {
    TIMConversation conversation =
        TIMManager.getInstance().getConversation(TIMConversationType.Group, mIdentify);
    Message message;
    if (mSwExcuse.isOn()) {
      message = new TextMessage("*a*d*开启全员禁言");
    } else {
      message = new TextMessage("*a*d*取消全员禁言");
    }
    conversation.sendMessage(message.getMessage(), new TIMValueCallBack<TIMMessage>() {
      @Override public void onError(int i, String s) {
        setSilenceSuc();
      }

      @Override public void onSuccess(TIMMessage timMessage) {
        MessageEvent.getInstance().onNewMessage(null);
      }
    });
    MessageEvent.getInstance().onNewMessage(message.getMessage());
  }

  @Override public void setSilenceFail() {
    mSwExcuse.setOn(!mSwNotiyType.isOn());
    showToast("设置失败，请稍后再试");
  }

  @Override public void isSilenceAll(boolean isSilence) {
    mSwExcuse.setOn(isSilence);
    // 全群禁言
    mSwExcuse.setOnSwitchStateChangeListener(isOn -> presenter.setSilence(mIdentify, isOn));
  }

  @Override public void updateGroupFaceUrl(String url) {
    Glide.with(mContext)
        .load(url)
        .apply(new RequestOptions()
            .bitmapTransform(new CropCircleTransformation())
            .placeholder(R.drawable.icon_conversation_de)
            .error(R.drawable.icon_conversation_de))
        .into(mIvPortrait);
  }

  @Override public void operationSuc() {
    popBackStack();
  }

  @Override protected void onFragmentResult(int requestCode, int resultCode, Intent data) {
    super.onFragmentResult(requestCode, resultCode, data);

    if (requestCode == VIP_INFO_REQCODE) {
      presenter.getGroupMembers(2, mIdentify);
    }

    if (resultCode == RESULT_OK) {
      if (requestCode == NAMECARD_REQUEST_CODE && null != data) {
        mTvGroupCard.setText(data.getStringExtra(ModifySingleTextFragment.INPUT_CONTENT_KEY));
      } else if (requestCode == GROUPNAME_REQUEST_CODE && null != data) {
        mTvName.setText(data.getStringExtra(ModifySingleTextFragment.INPUT_CONTENT_KEY));
      } else if (requestCode == DELETE_MEMBER_REQCODE && null != data) {
        presenter.getGroupMembers(2, mIdentify);
      } else if (requestCode == INVITE_MEMBER_REQCODE && null != data) {
        presenter.getGroupMembers(2, mIdentify);
      }
    }
  }

  @Override public void onActivityResult(int requestCode, int resultCode, Intent data) {
    super.onActivityResult(requestCode, resultCode, data);
    if (resultCode == ImagePicker.RESULT_CODE_ITEMS) {
      if (requestCode == PICK_IMAGE_REQCODE || requestCode == PICK_PHOTO_REQCODE) {
        // 选择图片、拍照完成
        ArrayList<ImageItem> images =
            (ArrayList<ImageItem>) data.getSerializableExtra(ImagePicker.EXTRA_RESULT_ITEMS);
        presenter.updateGroupFaceUrl(mIdentify, images.get(0).path);
      }
    }
  }

  @Subscribe(code = RxBusCode.NOTICE_CODE)
  public void editSuc(String title) {
    mTvNotice.setText(title);
  }

  @Override public void onDestroy() {
    super.onDestroy();
    RxBus.get().unRegister(this);
  }
}
